/**
 * Copyright (C) 2005-2009 Alfresco Software Limited.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

 * As a special exception to the terms and conditions of version 2.0 of 
 * the GPL, you may redistribute this Program in connection with Free/Libre 
 * and Open Source Software ("FLOSS") applications as described in Alfresco's 
 * FLOSS exception.  You should have recieved a copy of the text describing 
 * the FLOSS exception, and it is also available here: 
 * http://www.alfresco.com/legal/licensing
 */
 
if (typeof GWI == "undefined" || !GWI)
{
 var GWI = {};
} 
GWI.dashlet = GWI.dashlet || {};  

/**
 * Dashboard Site Tags component.
 * 
 * @namespace GWI
 * @class GWI.dashlet.RunChallenge
 */
(function()
{
   /**
    * YUI Library aliases
    */
   var Dom = YAHOO.util.Dom,
      Event = YAHOO.util.Event;

   /**
    * Alfresco Slingshot aliases
    */
   var $html = Alfresco.util.encodeHTML,
      $combine = Alfresco.util.combinePaths;

   /**
    * Preferences
    */
   //var PREFERENCES_DASHLET = "org.alfresco.share.dashlet",
   //   PREF_SITE_TAGS_FILTER = PREFERENCES_DASHLET + ".siteTagsFilter";


   /**
    * Dashboard SiteTags constructor.
    * 
    * @param {String} htmlId The HTML id of the parent element
    * @return {GWI.dashlet.RunChallenge} The new component instance
    * @constructor
    */
   GWI.dashlet.RunChallenge = function GWI_RunChallenge_constructor(htmlId)
   {
      return GWI.dashlet.RunChallenge.superclass.constructor.call(this, "GWI.dashlet.RunChallenge", htmlId);
   };

   /**
    * Extend from Alfresco.component.Base and add class implementation
    */
   YAHOO.extend(GWI.dashlet.RunChallenge, Alfresco.component.Base,
   {
      /**
       * Object container for initialization options
       *
       * @property options
       * @type object
       */
      options:
      {
         /**
          * Currently active filter.
          * 
          * @property activeFilter
          * @type string
          * @default "ALL"
          */
         activeFilter: "ALL"
      },

      /**
       * Body DOM container.
       * 
       * @property bodyContainer
       * @type object
       */
      bodyContainer: null,

      /**
       * Subscriber
       * 
       * @property subscriber
       * @type object
       */
       subscriber: null,
      
      /**
       * ContainerId for tag scope query
       *
       * @property containerId
       * @type string
       * @default ""
       */
      containerId: null,
      
      /**
       * Current view
       *
       * @property currentView
       * @type string
       * @default "DETAILS"
       */
      currentView: "DETAILS",

      /**
       * Active User
       *
       * @property activeUser
       * @type string
       * @default ""
       */
      activeUser: "",

      /**
       * Widgets
       *
       * @property widgets
       * @type object
       * @default {}
        */
      widgets: {},

      /**
       * Fired by YUI when parent element is available for scripting
       * @method onReady
       */
      onReady: function GWI_RunChallenge_onReady()
      {
         var me = this;
         
         // The body container
         this.bodyContainer = Dom.get(this.id + "-body");
         
         // Hook the run icons click
         Event.addListener(this.id + "-add", "click", this.addRun, this, true);
         Event.addListener(this.id + "-details", "click", this.showUserDetails, this, true);
         Event.addListener(this.id + "-history", "click", this.showUserHistory, this, true);
         Event.addListener(this.id + "-ranking", "click", this.showRanking, this, true);

         // Init widgets
         this.widgets.details = new GWI.dashlet.RunDetails(this.id + "-body").setOptions({});
         this.widgets.history = new GWI.dashlet.RunHistory(this.id + "-body").setOptions({});
         this.widgets.ranking = new GWI.dashlet.RunRanking(this.id + "-body").setOptions({});

         // Initialise the subscriber
         this.subscriber = new function () {
        	 YAHOO.util.Event.subscribe("SHOW_USER_DETAILS_CHANNEL", this, 'handleDetails');
        	 this.handleDetails = function (obj) {
        		 me.showUserDetails(obj.message);
        	 };  
        	 YAHOO.util.Event.subscribe("SHOW_HISTORY_CHANNEL", this, 'handleHistory');
        	 this.handleHistory = function (obj) {
        		 me.showUserHistory(obj.message, null);
        	 };  
         };
         
         // Dropdown filter
         this.widgets.filter = new YAHOO.widget.Button(this.id + "-filter",
         {
            type: "split",
            menu: this.id + "-filter-menu",
            disabled: true,
            lazyloadmenu: false
         });
         this.widgets.filter.on("click", this.onFilterClicked, this, true);
         // Clear the lazyLoad flag and fire init event to get menu rendered into the DOM
         var menu = this.widgets.filter.getMenu();
         menu.subscribe("click", function (p_sType, p_aArgs)
         {
            var menuItem = p_aArgs[1];
            if (menuItem)
            {
               me.widgets.filter.set("label", menuItem.cfg.getProperty("text"));
               me.onFilterChanged.call(me, p_aArgs[1]);
            }
         });
         
         if (this.options.activeFilter == "ALL")
         {
            this.widgets.filter.value = "runType";
            this.setActiveFilter("ALL");
         }
         else
         {
            this.widgets.filter.value = this.options.activeFilter;

            // Loop through and find the menuItem corresponding to the default filter
            var menuItems = menu.getItems(),
               menuItem,
               i, ii;

            for (i = 0, ii = menuItems.length; i < ii; i++)
            {
               menuItem = menuItems[i];
               if (menuItem.value == this.options.activeFilter)
               {
                  menu.clickEvent.fire(
                  {
                     type: "click"
                  }, menuItem);
                  break;
               }
            }
         }
         
         this.showUserDetails();

      },

      /**
       * Event handler for addRun click
       * @method addRun
       * @param e {object} Event
       */
      addRun: function GWI_RunChallenge_addRun(e)
      {
         GWI.dashlet.getAddRunInstance().show();
      },

      /**
       * Show user details
       * @method showUserDetails
       * @param username
       */
       showUserDetails: function GWI_RunChallenge_showUserDetails(username)
      {
         this.widgets.filter.set("disabled",true);
         this.currentView="DETAILS";
         if(typeof username != "string"){
        	 username = null;
         }
           // Hide the existing content
        this.widgets.details.showUserDetails(username);
      },

      /**
       * Show user history
       * @method showUserHistory
       * @param username
       * @param runType
       */
       showUserHistory: function GWI_RunChallenge_showUserHistory(username, runType)
      {
   	  		if(this.currentView != "HISTORY"){
   				this.currentView = "HISTORY";
   				this.widgets.filter.set("disabled",false);
   			}
           	if(typeof username != "string"){
           		username = "CURRENT_USER";
           	}
          	if(runType == null || runType =="" || typeof runType != "string"){
          		runType = this.options.activeFilter;
          	}
           	this.widgets.history.showUserHistory(username, runType);
    	   
      },
      /**
       * Show ranking
       * @method showRanking
       * @param runType
       */
       showRanking: function GWI_RunChallenge_showRanking(runType)
       {
    	  	if(this.currentView != "RANKING"){
	   			this.currentView = "RANKING";
	   			this.widgets.filter.set("disabled",false);
	   		}
          	if(typeof runType != "string"){
          		runType = this.options.activeFilter;
          	}
          	this.widgets.ranking.showRanking(runType);  
       }, 

      /**
       * Sets the active filter highlight in the UI
       * @method updateFilterUI
       */
      updateFilterUI: function GWI_RunChallenge_updateFilterUI()
      {
         switch (this.options.activeFilter)
         {
            case "ALL":
               Dom.removeClass(this.widgets.filter.get("element"), "yui-checkbox-button-checked");
               break;

            default:
               this.widgets.all.set("checked", false, true);
               Dom.addClass(this.widgets.filter.get("element"), "yui-checkbox-button-checked");
               break;
         }
      },

      /**
       * Saves active filter to user preferences
       * @method saveActiveFilter
       * @param filter {string} New filter to set
       * @param noPersist {boolean} [Optional] If set, preferences are not updated
       */
      setActiveFilter: function GWI_RunChallenge_saveActiveFilter(filter, noPersist)
      {
    	  this.options.activeFilter = filter;
    	  this.containerId = filter !== "ALL" ? filter : "";
    	  if(this.currentView == "HISTORY"){
    		  this.showUserHistory(this.activeUser, this.options.activeFilter)
    	  }
    	  else if(this.currentView == "RANKING"){
    		  this.showRanking(this.options.activeFilter)
    	  }
    	  //this.refreshTags();
    	  this.updateFilterUI();
      },

      /**
       * YUI WIDGET EVENT HANDLERS
       * Handlers for standard events fired from YUI widgets, e.g. "click"
       */

      /**
       * All tasks
       * @method onAllCheckedChanged
       * @param p_oEvent {object} Button event
       * @param p_obj {object} Button
       */
      onAllCheckedChanged: function GWI_RunChallenge_onAllCheckedChanged(p_oEvent, p_obj)
      {
         this.setActiveFilter("ALL");
         p_obj.set("checked", true, true);
      },

      /**
       * Filter button clicked event handler
       * @method onFilterClicked
       * @param p_oEvent {object} Dom event
       */
      onFilterClicked: function GWI_RunChallenge_onFilterClicked(p_oEvent)
      {
    	  alert("onfilterclicked");
    	  this.setActiveFilter(this.widgets.filter.value);
      },
      
      /**
       * Filter drop-down changed event handler
       * @method onFilterChanged
       * @param p_oMenuItem {object} Selected menu item
       */
      onFilterChanged: function GWI_RunChallenge_onFilterChanged(p_oMenuItem)
      {
         var filter = p_oMenuItem.value;
         this.widgets.filter.value = filter;
         this.setActiveFilter(filter);
      }
   });
})();
